<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8"  content="text/html"/>
    <title>WebSocket</title>
</head>
<body>
<noscript>
    <h2 style="color: #ff0000">浏览器不支持WebSocket</h2>
</noscript>
<div>
    <div>
        <button id="connect" onclick="connect()">连接</button>
        <button id="disconnect" onclick="disconnect()" disabled="disabled">断开连接</button>
     </div>
    <div id="conversationDiv">
        <label>输入你的名字</label>
        <input type="text" id="message" name="message"/>
        <button id="sendName" onclick="sendName()">发送</button>
        <p id="response"></p>
    </div>
</div>
<script type="text/javascript" th:src="@{/js/sockjs.min.js}"></script>
<script type="text/javascript" th:src="@{/js/stomp.min.js}"></script>
<script type="text/javascript" th:src="@{/js/jquery-3.2.1.js}"></script>
<script type="text/javascript">
    var stompCli = null;
    function setConnected(connected) {
        document.getElementById("connect").disabled = connected;
        document.getElementById("disconnect").disabled = !connected;
        document.getElementById("conversationDiv").style.visibility= connected ? 'visible' : 'hidden';
        $('#response').html();
    }
    
    function connect() {
        let socket = new SockJS('/endpointWisely');
        stompCli = Stomp.over(socket);
        stompCli.connect({},function (frame) {
            setConnected(true);
            console.log("Connected:" + frame);
            stompCli.subscribe('/topic/getResponse',function (response) {
                showResponse(JSON.parse(response.body).responseMessage);
            });
        });
    }
    function showResponse(message) {
        let response = $('#response');
        response.html(message);
    }
    
    function disconnect() {
        if( stompCli != null){
            stompCli.disconnect()
           // stompCli.disconnected();
        }
        setConnected(false);
        console.log("Disconnected");
    }

    function sendName(){
        let message = $('#message').val();
        console.log("send message is:" + message)
        stompCli.send("/welcome",{},JSON.stringify({'name':message}));
    }
</script>
</body>
</html>